package com.atguigu.java5;

import org.junit.Test;

import java.time.Duration;
import java.time.Instant;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.stream.LongStream;

/**
 * @author : leimingchao
 * @date Date : 2021年06月24日 21:39
 */
public class TestForkJoin {

    /**
     * ForkJoin框架
     */
    @Test
    public void test() {
        Instant start = Instant.now();
        ForkJoinPool forkJoinPool = new ForkJoinPool();
        ForkJoinTask<Long> task = new ForkJoinCalculate(0, 100000000000L);
        Long sum = forkJoinPool.invoke(task);
        System.out.println(sum);
        Instant end = Instant.now();
        //1亿：60毫秒
        //100亿：2067毫秒
        //500亿：13296毫秒
        //1000亿：22450毫秒
        System.out.println("耗费时间为：" + Duration.between(start, end).toMillis());
    }

    /**
     * 普通for
     */
    @Test
    public void test2() {
        Instant start = Instant.now();
        long sum = 0;
        for (long i = 0; i <= 100000000000L; i++) {
            sum += i;
        }
        System.out.println(sum);
        Instant end = Instant.now();
        //1亿：46毫秒
        //100亿：3608毫秒
        //500亿：20481毫秒
        //1000亿：34206毫秒
        System.out.println("耗费时间为：" + Duration.between(start, end).toMillis());
    }

    /**
     * java8 并行流
     */
    @Test
    public void test3() {
        Instant start = Instant.now();
        LongStream.rangeClosed(0,100000000000L)
                  .parallel()
                  .reduce(0,Long::sum);
        Instant end = Instant.now();
        //1000亿：8483毫秒
        System.out.println("耗费时间为：" + Duration.between(start, end).toMillis());
    }
}
